package com.example.qimo

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import com.example.qimo.R
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MemoActivity : AppCompatActivity() {

    private lateinit var editTextMemo: EditText
    private lateinit var buttonAddMemo: Button
    private lateinit var listViewMemo: ListView
    private lateinit var adapter: MemoAdapter
    private lateinit var sharedPreferences: SharedPreferences
    private var memos: MutableList<String> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_memo)

        editTextMemo = findViewById(R.id.editText_memo)
        buttonAddMemo = findViewById(R.id.button_add_memo)
        listViewMemo = findViewById(R.id.listView_memo)
        sharedPreferences = getPreferences(Context.MODE_PRIVATE)

        buttonAddMemo.setOnClickListener {
            addMemo()
        }

        loadMemos()
    }

    private fun addMemo() {
        val memo = editTextMemo.text.toString()
        if (memo.isNotEmpty()) {
            memos.add(memo)
            saveMemos(memos)
            loadMemos()
            editTextMemo.text.clear()
        }
    }

    private fun deleteMemo(position: Int) {
        memos.removeAt(position)
        saveMemos(memos)
        loadMemos()
    }

    private fun getMemos(): MutableList<String> {
        val memosJson = sharedPreferences.getString("memos", "[]")
        val typeToken = object : TypeToken<List<String>>() {}.type
        return Gson().fromJson(memosJson, typeToken)
    }

    private fun saveMemos(memos: List<String>) {
        val memosJson = Gson().toJson(memos)
        sharedPreferences.edit().putString("memos", memosJson).apply()
    }

    private fun loadMemos() {
        memos = getMemos()
        adapter = MemoAdapter(this, memos) { position ->
            deleteMemo(position)
        }
        listViewMemo.adapter = adapter
    }

    companion object {
        fun newIntent(context: Context): Intent {
            return Intent(context, MemoActivity::class.java)
        }
    }
}